/**
 * @file {处理ws相关}
 * @desc 前段发送的数据格式：JSON，
 * 具体的数据字段为:
 * {"deviceNum": port}
 * port为目检对应tcp端口号
 */
'use strict'

const webSocket = require('nodejs-websocket');
const {web_socket_config} = require('../config.json');

class Ws {

    deviceList = []
    /**
     * 初始化ws相关条件
     */
    constructor () {

        this.server = webSocket.createServer( (conn) =>{

            console.log(`${conn.headers.origin}连接客户端连接成功！`)
            conn.on('text', (msg) => {

                let data = JSON.parse(msg);
                if (data === 'heartCheck') {
                    console.log('heart');
                    conn.sendText('heart');
                } else if (data.deviceNumber){
                    this.deviceList.push({deviceKey: conn.key, deviceNumber: data.deviceNumber})
                    console.log(data);
                } else {
                    conn.sendText('请发用正确的数据格式!')
                }
            })

            conn.on('close', () => {
                console.log('连接关闭');
            })

            conn.on('error', (code, reason) => {
                console.log(`ws连接发生错误:${code},${reason}`);
            })

        }).listen(web_socket_config.port, web_socket_config.ip, () => console.log('ws服务启动'))
    }
    /**
     * 向目标目检工位发送缓存数据
     * @param {Number} port plc的哪个端口传过来的数据
     * @param {JSON} msg 命中的缓存数据
     */
     sendPanelInfo (port, msg) {
        console.log(this.deviceList);
        let deviceKey = null;
        // 找到port对应的连接的key
        this.deviceList.forEach(item => {
            if (item.deviceNumber == port) {
               deviceKey = item.deviceKey;
            }
        })
        // 发送到指定的目检浏览器
        this.server.connections.forEach((conn) => {
            if (deviceKey == conn.key) {
                conn.sendText(msg ? msg : JSON.stringify([]));
            }
        })
    }

    static getInstance () {
        if (Ws.instance) {
            return Ws.instance;
        } else {
            Ws.instance = new Ws();
            return Ws.instance;
        }
    }
}

module.exports = Ws;